package com.nowcoder.community.service;

import com.nowcoder.community.dao.elasticsearch.DiscussPostRepository;
import com.nowcoder.community.entity.DiscussPost;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ElasticsearchService {

    @Autowired
    private DiscussPostRepository discussPostRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    //add
    public void saveDiscussPost(DiscussPost discussPost) {
        discussPostRepository.save(discussPost);
    }

    //delete
    public void deleteDiscussPost(int id) {
        discussPostRepository.deleteById(id);
    }

    //select
    public Map<String, Object> searchDiscussPost(String keyword, int current, int limit) {

        Sort sort = Sort.by("score").descending()
                .and(Sort.by("type").descending())
                .and(Sort.by("createTime").descending());

        int count = discussPostRepository.findDiscussPostByTitleLikeOrContentLike(keyword,keyword, Pageable.unpaged()).size();
        List<SearchHit<DiscussPost>> hitPosts = discussPostRepository
                .findDiscussPostByTitleLikeOrContentLike(keyword, keyword, PageRequest.of(current, limit, sort));

        List<DiscussPost> posts = new ArrayList<>();
        hitPosts.forEach(res-> {
            DiscussPost post = res.getContent();
            post.setTitle(StringUtils.strip(res.getHighlightField("title").toString(),"[]"));
            post.setContent(StringUtils.strip(res.getHighlightField("content").toString(),"[]"));
            posts.add(post);
        });

        Map<String, Object> map = new HashMap<>();
        map.put("count",count);
        map.put("posts",posts);

        return map;
    }
}
